package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.model.dto.ReadBehaviorDto;
import com.heima.behavior.model.pojo.ApReadBehavior;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.behavior.utils.AppThreadLocalUtil;
import com.heima.common.constants.KafkaMessageConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.message.UpdateArticleMess;
import com.heima.model.user.entity.ApUser;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private KafkaTemplate kafkaTemplate;


    /**
     * 阅读行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //1.参数校验
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        Long userId = AppThreadLocalUtil.getId();
        if (userId == null && dto.getEquipmentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.查询用户的阅读行为
        Criteria criteria = new Criteria()
                .orOperator(Criteria.where("userId").is(userId), Criteria.where("equipmentId").is(dto.getEquipmentId()))
                .andOperator(Criteria.where("articleId").is(dto.getArticleId()));
        Query query = Query.query(criteria);
        ApReadBehavior readBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);
        //2.1如果存在，更新其参数信息
        if (readBehavior != null) {
            readBehavior.setCount(readBehavior.getCount() + 1);
            readBehavior.setUpdatedTime(new Date());
            readBehavior.setReadDuration(dto.getReadDuration());
            mongoTemplate.save(readBehavior);
        } else {
            //2.2如果不存在，创建一个新的对象并封装参数信息
            readBehavior = new ApReadBehavior();
            readBehavior.setReadDuration(dto.getReadDuration());
            readBehavior.setUpdatedTime(new Date());
            readBehavior.setArticleId(dto.getArticleId());
            readBehavior.setCount(1);
            readBehavior.setCreatedTime(new Date());
            readBehavior.setLoadDuration(dto.getLoadDuration());
            readBehavior.setPercentage(dto.getPercentage());
            readBehavior.setUserId(userId);
            readBehavior.setEquipmentId(dto.getEquipmentId());
            mongoTemplate.save(readBehavior);
        }

        //发送行为消息
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setAdd(1);
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        kafkaTemplate.send(KafkaMessageConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(mess));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
